<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="学号" prop="studentId" label-width="3em">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name" label-width="3em">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="民族" prop="nation" label-width="3em">
        <el-input
          v-model="queryParams.nation"
          placeholder="请输入民族"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="政治面貌" prop="politicalStatus">
        <el-input
          v-model="queryParams.politicalStatus"
          placeholder="请输入政治面貌"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col
        :span="1.5"
        v-show="
          (archiveList.length === 0 && userRoles[0] == 'student') ||
          userRoles[0] != 'student'
        "
      >
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:archive:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:archive:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5" v-show="userRoles[0] != 'student'">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:archive:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5" v-show="userRoles[0] != 'student'">
        <el-button
          type="warning"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['manage:archive:add']"
          >批量导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:archive:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="archiveList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="studentId" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="年级" align="center">
        <template #default="{ row }"> {{ row.grade || "-" }}级 </template>
      </el-table-column>
      <el-table-column label="专业" align="center">
        <template #default="{ row }">
          <div v-for="item in majorList" :key="item.majorId">
            <span v-if="item.majorId == row.majorId">{{ item.majorName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="班级" align="center">
        <template #default="{ row }"> {{ row.classe || "-" }}班 </template>
      </el-table-column>
      <!-- <el-table-column
        label="身份证号"
        align="center"
        prop="idCard"
        width="170"
      />
      <el-table-column label="民族" align="center" prop="nation" width="70" />
      <el-table-column
        label="政治面貌"
        align="center"
        prop="politicalStatus"
        width="120"
      /> -->
      <!-- <el-table-column label="籍贯" align="center" prop="nativePlace" /> -->
      <!-- <el-table-column label="照片路径" align="center" prop="photo" width="120">
        <template #default="scope">
          <image-preview :src="scope.row.photo" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="入学日期"
        align="center"
        prop="admissionDate"
        width="100"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.admissionDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="预计毕业日期"
        align="center"
        prop="graduationDate"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.graduationDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="学籍状态"
        align="center"
        prop="studentStatus"
        width="80"
      >
        <template #default="scope">
          <dict-tag
            :options="student_status"
            :value="scope.row.studentStatus"
          />
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleGetLog(scope.row)"
            v-hasPermi="['manage:archive:edit']"
            >查看日志</el-button
          >
          <el-button link type="primary">
            <router-link
              :to="{
                path: '/manage/stuInfo/index/' + scope.row.studentId,
                query: { form: JSON.stringify(scope.row) },
              }"
              class="link-type"
            >
              <span style="color: #409eff">查看详情</span>
            </router-link>
          </el-button>
          <!-- <el-button
            link
            type="primary"
            @click="testr(scope.row)"
            v-hasPermi="['manage:archive:edit']"
            >test</el-button
          > -->
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:archive:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:archive:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生档案管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form
        ref="archiveRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="照片路径" prop="photo">
              <image-upload v-model="form.photo" />
            </el-form-item>
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="form.studentId" placeholder="请输入学号" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年级" prop="grade">
              <el-input v-model="form.grade" placeholder="请输入年级" />
            </el-form-item>
            <el-form-item label="专业" prop="majorId">
              <el-select v-model="form.majorId" placeholder="请选择专业">
                <el-option
                  v-for="item in majorList"
                  :key="item.majorId"
                  :label="item.majorName"
                  :value="item.majorId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级" prop="classe">
              <el-input v-model="form.classe" placeholder="请输入班级" />
            </el-form-item>
            <el-form-item label="学籍状态" prop="studentStatus">
              <el-select
                v-model="form.studentStatus"
                placeholder="请选择学籍状态"
              >
                <el-option
                  v-for="dict in student_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                clearable
                v-model="form.birthDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择出生日期"
              />
            </el-form-item>
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="民族" prop="nation">
              <el-input v-model="form.nation" placeholder="请输入民族" />
            </el-form-item>
            <el-form-item label="政治面貌" prop="politicalStatus">
              <el-input
                v-model="form.politicalStatus"
                placeholder="请输入政治面貌"
              />
            </el-form-item>
            <el-form-item label="籍贯" prop="nativePlace">
              <el-input v-model="form.nativePlace" placeholder="请输入籍贯" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入学日期" prop="admissionDate">
              <el-date-picker
                clearable
                v-model="form.admissionDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择入学日期"
              />
            </el-form-item>
            <el-form-item label="毕业日期" prop="graduationDate">
              <el-date-picker
                clearable
                v-model="form.graduationDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择预计毕业日期"
              />
            </el-form-item>
            <el-form-item label="学校" prop="school">
              <el-input v-model="form.school" placeholder="请输入所在学校" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="学历" prop="highestEducation">
              <el-input
                v-model="form.highestEducation"
                placeholder="请输入最高全日制学历"
              />
            </el-form-item>
            <el-form-item
              label="职业资格及职称"
              prop="professionalQualification"
            >
              <el-input
                v-model="form.professionalQualification"
                placeholder="如：高级软件开发工程师等"
              />
            </el-form-item>
            <el-form-item label="职业技能证书" prop="certificateName">
              <el-input-tag
                v-model="form.certificateName"
                tag-type="primary"
                placeholder="请输入职业技能证书名称,按回车添加"
              />
            </el-form-item>
            <el-form-item label="教育背景" prop="educationBackground">
              <el-input
                v-model="form.educationBackground"
                placeholder="比如详细的教育经历"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
            <el-form-item label="实习经历" prop="internshipExperience">
              <el-input
                v-model="form.internshipExperience"
                placeholder="请填写实习经历(时间、地点、负责工作)"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
            <el-form-item label="自我评价" prop="selfEvaluation">
              <el-input
                v-model="form.selfEvaluation"
                type="textarea"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加查看日志对话框 -->
    <el-dialog v-model="openLog" title="查看日志" width="900px" append-to-body>
      <!-- 添加日志表格 -->
      <el-table :data="logList" border stripe>
        <el-table-column
          label="logHash"
          prop="logHash"
          align="center"
          width="120"
        />
        <el-table-column
          label="操作类型"
          prop="operationType"
          align="center"
          width="80"
        >
          <template #default="scope">
            <dict-tag
              :options="sys_oper_type"
              :value="scope.row.operationType"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="请求参数"
          prop="operationParam"
          align="center"
          width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="操作人"
          prop="operatorName"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          label="IP地址"
          prop="operationIp"
          align="center"
        ></el-table-column>
        <el-table-column label="操作时间" prop="operationTime" align="center">
          <template #default="scope">
            <span>{{
              parseTime(scope.row.operationTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="transactionHash"
          prop="transactionHash"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
    </el-dialog>
    <!-- 添加批量导入对话框 -->
    <el-dialog title="数据导入" v-model="excelOpen">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="uploadExcelUrl"
        :headers="headers"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :before-upload="handleBeforeUpload"
        :limit="1"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">上传文件 </el-button>
        </template>

        <el-button class="ml-3" type="success" @click="submitUpload">
          上传
        </el-button>

        <template #tip>
          <div class="el-upload__tip">
            上传文件仅支持xls/xlsx,大小不能超过1MB
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup name="Archive">
import {
  listArchive,
  getArchive,
  delArchive,
  addArchive,
  updateArchive,
} from "@/api/manage/archive";
import { getArchiveLogByStudentId } from "@/api/manage/archiveLog";
import { listMajor } from "@/api/manage/major";
import { loadAllParams } from "@/api/page";
import router from "@/router/index";
import { getCertificateNameByStudentId } from "@/api/manage/certificate";
import { getToken } from "@/utils/auth";
import { get } from "@vueuse/core";
import useUserStore from "@/store/modules/user";

//获取登录用户角色
const userStore = useUserStore();
const userRoles = userStore.roles;

const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");
const { student_status } = proxy.useDict("student_status");
const { sys_oper_type } = proxy.useDict("sys_oper_type");

const archiveList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const openLog = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    name: null,
    nation: null,
    politicalStatus: null,
  },
  rules: {
    studentId: [{ required: true, message: "学号不能为空", trigger: "blur" }],
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
    gender: [{ required: true, message: "性别不能为空", trigger: "change" }],
    majorId: [{ required: true, message: "专业不能为空", trigger: "change" }],
    grade: [{ required: true, message: "年级不能为空", trigger: "blur" }],
    classe: [{ required: true, message: "班级不能为空", trigger: "blur" }],
    birthDate: [
      { required: true, message: "出生日期不能为空", trigger: "blur" },
    ],
    idCard: [{ required: true, message: "身份证号不能为空", trigger: "blur" }],
    nation: [{ required: true, message: "民族不能为空", trigger: "blur" }],
    politicalStatus: [
      { required: true, message: "政治面貌不能为空", trigger: "blur" },
    ],
    nativePlace: [{ required: true, message: "籍贯不能为空", trigger: "blur" }],
    photo: [{ required: true, message: "照片路径不能为空", trigger: "blur" }],
    admissionDate: [
      { required: true, message: "入学日期不能为空", trigger: "blur" },
    ],
    graduationDate: [
      { required: true, message: "预计毕业日期不能为空", trigger: "blur" },
    ],
    studentStatus: [
      { required: true, message: "学籍状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生档案管理列表 */
function getList() {
  loading.value = true;
  listArchive(queryParams.value).then((response) => {
    archiveList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  console.log(userRoles[0]);
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    studentId: null,
    name: null,
    gender: null,
    birthDate: null,
    idCard: null,
    nation: null,
    politicalStatus: null,
    nativePlace: null,
    photo: null,
    admissionDate: null,
    graduationDate: null,
    studentStatus: "1",
    createTime: null,
    updateTime: null,
    grade: null,
    majorId: null,
    classe: null,
    phone: null,
    email: null,
    school: "山东青年政治学院",
    highestEducation: null,
    languageAbility: null,
    educationBackgroun: null,
    professionalQualification: null,
    internshipExperience: null,
    selfEvaluation: null,
  };
  proxy.resetForm("archiveRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.studentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生档案管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _studentId = row.studentId || ids.value;
  getArchive(_studentId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改学生档案管理";
    getCertificateNameByStudentId(_studentId).then((response) => {
      form.value.certificateName = response.data;
      console.log(form.value);
    });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["archiveRef"].validate((valid) => {
    if (valid) {
      if (form.value.studentId != null) {
        updateArchive(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArchive(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _studentIds = row.studentId || ids.value;
  proxy.$modal
    .confirm('是否确认删除学生档案管理编号为"' + _studentIds + '"的数据项？')
    .then(function () {
      return delArchive(_studentIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/archive/export",
    {
      ...queryParams.value,
    },
    `archive_${new Date().getTime()}.xlsx`
  );
}

/**打开批量导入窗口 */
const excelOpen = ref(false);
function handleImport() {
  excelOpen.value = true;
}

/**上传excel文件 */
const uploadRef = ref({});
function submitUpload() {
  uploadRef.value.submit();
}
/**上传excel文件地址 接口 */
const uploadExcelUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/manage/archive/import"
);
/**上传请求头 */
const headers = ref({ Authorization: "Bearer " + getToken() });
// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code === 200) {
    proxy.$modal.msgSuccess("导入成功");
    excelOpen.value = false;
    getList();
  } else {
    proxy.$modal.msgError(res.msg);
  }
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

// 上传失败
function handleUploadError() {
  proxy.$modal.msgError("上传excel失败");
  uploadRef.value.clearFiles();
  proxy.$modal.closeLoading();
}

//校验导入文件
const props = defineProps({
  modelValue: [String, Object, Array],
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 1,
  },
  // 文件类型, 例如['xls', 'xlsx']
  fileType: {
    type: Array,
    default: () => ["xls", "xlsx"],
  },
});
// 上传前loading加载
function handleBeforeUpload(file) {
  let isExcel = false;
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    isExcel = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
  }
  if (!isExcel) {
    proxy.$modal.msgError(
      `文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`
    );
    return false;
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传excel，请稍候...");
}

/** 查看日志 */
const logList = ref([]);
function handleGetLog(row) {
  openLog.value = true;
  getArchiveLogByStudentId(row.studentId).then((response) => {
    logList.value = response.data;
  });
}

/**获取专业数据 */
const majorList = ref([]);
function getMajorList() {
  listMajor(loadAllParams).then((response) => {
    majorList.value = response.rows;
  });
}
/**路由跳转携带参数 */
function testr(row) {
  console.log("/manage/stuInfo/index/" + row.studentId);
  router.push({
    path: "/manage/stuInfo/index/" + row.studentId,
    query: {
      form: JSON.stringify(row),
    },
  });
}

getMajorList();
getList();
</script>
